package com.crm.base.config;



import com.crm.base.domain.AjaxResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private ObjectMapper mapper;
    @Autowired
    private TokenFilter filter;
    protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authorizeRequests().antMatchers("/user/login").permitAll()
        .anyRequest().fullyAuthenticated()
        .and()
        .exceptionHandling().authenticationEntryPoint((a,b,c)->{
            b.setContentType("application/json");
            b.getWriter().write(mapper.writeValueAsString(AjaxResult.me("用户名或密码错误")));
        })
        .accessDeniedHandler((a,b,c)->{
            b.setContentType("application/json");
            b.getWriter().write(mapper.writeValueAsString(AjaxResult.me("没有权限|NO PERMISSIONS")));
        })
        .and()
        .addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class)
        .cors();

    }

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

}
